package cc.rengu.igas.mcps.core.service.trans.common;

import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.igas.mcps.core.service.base.ManageService;
import cc.rengu.igas.mcps.facade.bean.*;
import cc.rengu.igas.mcps.facade.request.PosParamDownloadRequest;
import cc.rengu.igas.mcps.facade.response.PosParamDownloadResponse;
import cc.rengu.igas.share.core.model.*;
import cc.rengu.igas.share.core.realize.BompService;
import cc.rengu.igas.share.core.realize.MchntService;
import cc.rengu.igas.share.core.realize.impl.BompServiceImpl;
import cc.rengu.igas.share.core.realize.impl.MchntServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * POS终端参数下发	M00MC005
 */
public class TermParamDownloadService extends ManageService {

    @Override
    protected Object bizBeforeCust() throws Exception {
        PosParamDownloadRequest posParamDownloadRequest = new PosParamDownloadRequest();
        ConvertUtil.convertOutput(posParamDownloadRequest);
        return posParamDownloadRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        /*初始化请求报文resqust*/
        PosParamDownloadRequest posParamDownloadRequest = (PosParamDownloadRequest) request;
        PosParamDownloadResponse posParamDownloadResponse = new PosParamDownloadResponse();
        BizResponse bizResponse = new BizResponse();
        String paramType = posParamDownloadRequest.getParamType();
        /*下载索引是TLV格式的 数据*/
        String mchntNo = posParamDownloadRequest.getMchntNo();
        String termNo = posParamDownloadRequest.getTermNo();
        /* 获取EMV参数信息 */
        String instId = posParamDownloadRequest.getHeader().getInstId();
        BompService bompService = new BompServiceImpl();
        List<EmvParamInfo> emvParamInfoList = bompService.getEmvParamInfo(instId);
        if (null == emvParamInfoList || emvParamInfoList.isEmpty()) {
            rglog.error("EMV配置参数为空!");
            throw new BizException(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode(), RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
        }
        /* Step 1 ：获取参数详细信息*/
        MchntService mchntService = new MchntServiceImpl();
        MchntTermInfo mchntTermInfo = mchntService.getMchntTermInfo(instId, mchntNo, termNo);
        /*pos参数不区分法人行*/
        if ("01".equals(paramType)) {
            //common参数
            MchntInfo mchntInfo = mchntService.getMchntInfo(posParamDownloadRequest.getHeader().getInstId(), mchntNo);
            //查询普通终端参数信息
            CommonParam commonParam = new CommonParam();
            commonParam.setTimeOut("60");//超时时间 默认60秒
            commonParam.setRetryTime("3"); //重试次数
            commonParam.setTelePhoneNo(mchntTermInfo.getContactPhone()); //管理电话号码
            commonParam.setSurpManEnter("0"); //是否支持手输卡号
            commonParam.setResendTime("3"); //交易重发次数
            commonParam.setMchntName(mchntInfo.getMchntName()); //商户名称
            //交易列表  从商户业务权限控制表获取控制分组类型
            //根据终端号查询权限
            List<MchntAuthInfo> mchntAuthInfoList = mchntService.getMchntAuthInfo(posParamDownloadRequest.getHeader().getInstId(), mchntNo, termNo);
            if (CollectionUtils.isEmpty(mchntAuthInfoList)) {
                //查询商户权限数据
                mchntAuthInfoList = mchntService.getMchntAuthInfo(posParamDownloadRequest.getHeader().getInstId(), mchntNo, null);
            }


            if (!CollectionUtils.isEmpty(mchntAuthInfoList)) {
                mchntAuthInfoList = mchntAuthInfoList.stream().filter(item -> AppParamConstant.YES.equals(item.getSupportFlag())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(mchntAuthInfoList)) {
                    List<TransAuth> transAuthList = new ArrayList<>();
                    Map<String, List<TransInfo>> map = new HashMap();
                    for (MchntAuthInfo mchntAuthInfo : mchntAuthInfoList) {
                        List<TransInfo> list = new ArrayList<>();
                        if (map.containsKey(mchntAuthInfo.getTxnGroup())) {
                            TransInfo transInfo = new TransInfo();
                            transInfo.setTxnNum(mchntAuthInfo.getTxnNum());
                            transInfo.setTxnName(mchntAuthInfo.getTxnName());
                            map.get(mchntAuthInfo.getTxnGroup()).add(transInfo);
                        } else {
                            TransInfo transInfo = new TransInfo();
                            transInfo.setTxnNum(mchntAuthInfo.getTxnNum());
                            transInfo.setTxnName(mchntAuthInfo.getTxnName());
                            list.add(transInfo);
                            map.put(mchntAuthInfo.getTxnGroup(), list);
                        }
                    }
                    Iterator<Map.Entry<String, List<TransInfo>>> it = map.entrySet().iterator();
                    while (it.hasNext()) {
                        TransAuth transAuth = new TransAuth();
                        Map.Entry<String, List<TransInfo>> en = it.next();
                        transAuth.setTxnGroup(en.getKey());
                        transAuth.setTransInfoList(en.getValue());
                        transAuthList.add(transAuth);
                    }
                    commonParam.setTransAuthList(transAuthList);
                }
            }

            String noPinFlag = "0";
            String noSignFlag = "0";
            if (AppParamConstant.YES.equals(mchntInfo.getNoPasswordFlag())) {
                noPinFlag = "1";  //免密
            }

            commonParam.setNoPinFlag(noPinFlag); //免密标志
            if (!StringUtil.isEmptyOrNull(mchntInfo.getNoPasswordAmt())) {
                commonParam.setNoPinAmt(String.valueOf(Integer.getInteger(mchntInfo.getNoPasswordAmt()) * 100));//免密金额
            }
            commonParam.setNoSignFlag(noSignFlag); //免签标识
//            commonParam.setNoSignAmt(String.valueOf(merOffline.getNoSignLimit() * 100)); //免签限额
            String ifFastFlag = "0";
            commonParam.setNoTouchQuickFlag(ifFastFlag); //启用非接快速业务服务标识

            String TOFlag = "0";
            /*商户结算账户信息全局变量*/
            List<MchntAcctInfo> mchntAcctInfoList = mchntService.getMchntAcctInfo(posParamDownloadRequest.getHeader().getInstId(), mchntNo);
            Optional<MchntAcctInfo> mchntAcctInfoOpt = mchntAcctInfoList.stream().filter(item -> item.getFundType().equals("00")).findFirst();
            if (mchntAcctInfoOpt.isPresent() && "T0".equals(mchntAcctInfoOpt.get().getSettleAcctType())) {
                TOFlag = "1";
            }
            commonParam.setT0Flag(TOFlag); //是否T0商户
            commonParam.setAutoSignOut(mchntTermInfo.getAutoSignOutFlag()); //是否自动签退
            List<CommonParam> commonParamList = new ArrayList<>();
            commonParamList.add(commonParam);
            posParamDownloadResponse.setCommonParamList(commonParamList);

        } else if ("02".equals(paramType)) {
            //IC卡公钥
            emvParamInfoList = emvParamInfoList.stream().filter(item -> item.getUsageKey().equals("0")).collect(Collectors.toList());
            handleIcPublicKey(posParamDownloadResponse, emvParamInfoList);
            mchntTermInfo.setIcKeyDownFlag("1");
            mchntService.updateMchntTermInfo("03", mchntTermInfo);
        } else if ("03".equals(paramType)) {
            //IC卡参数
            emvParamInfoList = emvParamInfoList.stream().filter(item -> item.getUsageKey().equals("1")).collect(Collectors.toList());
            handleIcAppParam(posParamDownloadResponse, emvParamInfoList);
            mchntTermInfo.setIcParamDownFlag("1");
            mchntService.updateMchntTermInfo("02", mchntTermInfo);
        } else {
            rglog.debug("暂不支持此类型参数下载");
            bizResponse.setRspSysId(AppParamConstant.IGAS);
            bizResponse.setRespCode(RespCodeEnum.NOT_SURPPORT_PARAM_TYPE_ERROR.getRespCode());
            bizResponse.setRespDesc(RespCodeEnum.NOT_SURPPORT_PARAM_TYPE_ERROR.getRespDesc());
            return bizResponse;
        }


        /* Step 2 ：重组响应结果 */
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(posParamDownloadResponse);
        return bizResponse;
    }

    private void handleIcAppParam(PosParamDownloadResponse posParamDownloadResponse, List<EmvParamInfo> emvParamInfoList) {
        List<IcAppParam> icAppParamList = new ArrayList<>();
        if (null != emvParamInfoList && !emvParamInfoList.isEmpty()) {
            for (EmvParamInfo emvParamInfo : emvParamInfoList) {
                IcAppParam icAppParam = new IcAppParam();
                icAppParam.setKeyIndex(emvParamInfo.getParamIndex());
                icAppParam.setAppData(emvParamInfo.getParamValue());
                icAppParamList.add(icAppParam);
            }
            posParamDownloadResponse.setIcAppParamList(icAppParamList);
        }
    }

    private void handleIcPublicKey(PosParamDownloadResponse posParamDownloadResponse, List<EmvParamInfo> emvParamInfoList) {
        List<IcPublicKey> icPublicKeyList = new ArrayList<>();
        if (null != emvParamInfoList && !emvParamInfoList.isEmpty()) {
            for (EmvParamInfo emvParamInfo : emvParamInfoList) {
                IcPublicKey icPublicKey = new IcPublicKey();
                icPublicKey.setPubKeyIndex(emvParamInfo.getParamIndex());
                icPublicKey.setPublicKey(emvParamInfo.getParamValue());
                icPublicKeyList.add(icPublicKey);
            }
            posParamDownloadResponse.setIcPublicKeyList(icPublicKeyList);
        }
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        PosParamDownloadResponse posParamDownloadResponse = (PosParamDownloadResponse) bizResponse.getResult();
        ConvertUtil.convertInput(posParamDownloadResponse);
    }
}
